import { Controller, Post, Body, UseInterceptors, UploadedFile } from '@nestjs/common';
import { UsersService } from './users.service';
import { OcrService } from '../ocr.service';
import { IflytekOcrService } from '../iflytek-ocr.service';
import { diskStorage } from 'multer';
import { extname } from 'path';
import { FileInterceptor } from '@nestjs/platform-express';

//核心功能，上传图片之后，使用ocr识别图片中的文字，然后保存到mysql数据库中，返回识别结果

@Controller('users')
export class UsersController {
  constructor(
    private readonly usersService: UsersService,
    private readonly ocrService: OcrService,
    private readonly iflytekOcrService: IflytekOcrService,
  ) {}

  @Post()
  addUser(@Body() user: any) {
    return this.usersService.addUser(user);
  }

  @Post('ocr')
  @UseInterceptors(FileInterceptor('image', {
    storage: diskStorage({
      destination: './uploads', // 图片保存的目录
      filename: (req, file, cb) => {
        const randomName = Array(32).fill(null).map(() => (Math.round(Math.random() * 16)).toString(16)).join('');
        return cb(null, `${randomName}${extname(file.originalname)}`);
      },
    }),
  }))
  async ocrImage(@UploadedFile() file) {
    const imagePath = file.path;
    const result = await this.ocrService.recognizeImage(imagePath);
    // 保存到 mysql
    return { result };
  }
  // async ocrImage(@Body() body: { imagePath: string }) {
  //   const result = await this.ocrService.recognizeImage(body.imagePath);
  //   // 保存mysql
  //   return { result };
  // }

  @Post('iflytek-ocr')
  async iflytekOcr(@Body() body: { imagePath: string }) {
    const result = await this.iflytekOcrService.recognizeImage(body.imagePath);
    return { result };
  }
}
